//
//  UIlabel+Extensions.swift
//  HomeShop
//
//  Created by 刘泽 on 2018/2/10.
//  Copyright © 2018年 刘泽. All rights reserved.
//

import Foundation
import UIKit

extension UILabel {

    open override func awakeFromNib() {
        super.awakeFromNib()
        if text == "Label"{
            text = nil
        }

    }

    /**
     The content size of UILabel

     - returns: CGSize
     */
    public func contentSize() -> CGSize {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = self.lineBreakMode
        paragraphStyle.alignment = self.textAlignment
        let attributes: [NSAttributedStringKey : Any] = [NSAttributedStringKey.font: self.font, NSAttributedStringKey.paragraphStyle: paragraphStyle]
        let contentSize: CGSize = self.text!.boundingRect(
            with: self.frame.size,
            options: ([.usesLineFragmentOrigin, .usesFontLeading]),
            attributes: attributes,
            context: nil
            ).size
        return contentSize
    }

    /**
     Set UILabel's frame with the string, and limit the width.

     - parameter string: text
     - parameter width:  your limit width
     */
    public func setFrameWithString(_ string: String, width: CGFloat) {
        self.numberOfLines = 0
        let attributes: [NSAttributedStringKey : Any] = [
            NSAttributedStringKey.font: self.font,
            ]
        let resultSize: CGSize = string.boundingRect(
            with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude),
            options: NSStringDrawingOptions.usesLineFragmentOrigin,
            attributes: attributes,
            context: nil
            ).size
        let resultHeight: CGFloat = resultSize.height
        let resultWidth: CGFloat = resultSize.width
        var frame: CGRect = self.frame
        frame.size.height = resultHeight
        frame.size.width = resultWidth
        self.frame = frame
    }




}
